import React, {useEffect, useRef, useState} from 'react';
import {
    Button, Card,
    Drawer,
    Form,
    Image,
    Input, InputNumber, message, Modal,
    Select,
    Space,
    Table,
    Tabs, Tooltip, Typography,
    Upload
} from "antd";
import {DeleteFilled, EditOutlined, LoadingOutlined, PlusOutlined,} from "@ant-design/icons";
import {
    reqAddNewCourse,
    reqDeleteCourseById,
    reqEditCourse,
    reqGetCourseList
} from "../../../api/backStage/backStageApi";
import {debounce} from "lodash";
import axios from "axios";

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const AdminCourse = () => {


    const [drawerOpen, setDrawerOpen] = useState(false);
    const [courseData, setCourseData] = useState([])

    const [editCourse, setEditCourse] = useState(false)

    const [deleteOpen, setDeleteOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [courseId, setCourseId] = useState(null)

    const [tabKey, setTabKey] = useState("book")

    const [editCoverLoading, setEditCoverLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState(null)


    const [form] = Form.useForm();


    useEffect(() => {
        getCourseListData()
    }, [])

    useEffect(() => {
        if (editCourse) {
            form.setFieldsValue({
                cover: imageUrl
            })
        }
    }, [imageUrl])
    //获取表格数据
    const getCourseListData = async () => {
        const result = await reqGetCourseList()
        setCourseData(result.data)
    }

    const showDrawer = () => {
        setEditCourse(false)
        form.resetFields()
        setDrawerOpen(true);
    };
    const drawerClose = () => {
        setDrawerOpen(false);
    }


    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            render: (_, record) => {
                return <Image width={100} src={record.cover}></Image>
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
        },
        {
            title: '作者',
            dataIndex: 'author_name',
        },
        {
            title: '简介',
            dataIndex: 'describe',
            render: text => <span style={{color: '#aaa'}}>{text}</span>
        },
        {
            title: '类型',
            dataIndex: 'cate',
            width: 250
        },
        {
            title: '价格',
            dataIndex: 'now_price',
            render: text => <span style={{color: 'red'}}>{text}</span>
        },
        {
            title: '操作',
            align: 'center',
            dataIndex: 'handle',
            render: (_, record) => {
                return (
                    <Typography.Link>
                        <Space size="large">
                            <Tooltip title="修改">
                                <Button onClick={() => updateCourse(record)} style={{background: '#ffa500'}}
                                        type="primary">
                                    <EditOutlined/>
                                </Button>
                            </Tooltip>
                            <Tooltip title="删除">
                                <Button onClick={() => {
                                    setDeleteOpen(true)
                                    setCourseId(record.id)
                                }} type="primary" danger>
                                    <DeleteFilled/>
                                </Button>
                            </Tooltip>
                        </Space>
                    </Typography.Link>
                );
            },
        },
    ];

    //筛选分类
    const handleChange = async (cate) => {
        const result = await reqGetCourseList()
        setCourseData(result.data.filter((item) => item.cate.indexOf(cate) !== -1))
    };

    //搜索课程
    const searchCourse = debounce(async (e) => {
        const result = await reqGetCourseList()
        setCourseData(result.data.filter((item) => item.title.indexOf(e.target.value) !== -1))
    }, 500)

    //修改
    const updateCourse = (course) => {
        setEditCourse(true)
        setCourseId(course.id)
        setDrawerOpen(true)
        setImageUrl([course.cover])
        console.log(course)
        if (form) {
            form.setFieldsValue({
                ...course,
                cover: imageUrl
            })
        }
    }

    //添加课程和修改
    const confirmAdd = async () => {
        if (editCourse) {
            try {
                const fd = form.getFieldValue()
                console.log(fd)
                const result = await reqEditCourse({course_id: courseId, fd})
                setDrawerOpen(false)
                if (result.status === 0) {
                    getCourseListData()
                    message.success('修改课程成功!')
                } else {
                    message.error('修改课程失败!')
                }
            } catch (err) {
                message.error(err)
            }
        } else {
            try {
                const fd = form.getFieldValue()
                const result = await reqAddNewCourse({fd})
                setDrawerOpen(false)
                if (result.status === 0) {
                    getCourseListData()
                    message.success('添加课程成功!')
                } else {
                    message.error('添加课程失败!')
                }
            } catch (err) {
                message.error(err)
            }
        }
    }

    const handleTabClick = (key, event) => {
        setTabKey(key)
    }

    //自定义上传
    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/admin/course-page/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            const error = new Error("Some error");
            onError(err);
        }
    }
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }

    const uploadHandleChange = (info) => {
        if (info.file.status === 'uploading') {
            setEditCoverLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (url) => {
                setEditCoverLoading(false);
                setImageUrl([url]);
            });
        }
    };

    const uploadButton = (
        <div>
            {editCoverLoading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8}}>
                Upload
            </div>
        </div>
    );


    const tabItems = [
        {
            key: 'book',
            label: editCourse ? '修改书籍' : '添加书籍',
            children: <Form
                form={form}
                style={{paddingTop: 30}}
                name="courseForm"
                labelCol={{span: 6}}
                wrapperCol={{span: 14}}
                layout="horizontal"
            >
                <Form.Item label="课程标题" name="title"
                           rules={[{required: true, message: "请输入标题!"}]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="作者" name="author_name"
                           rules={[{required: true, message: "请输入作者名字!"}]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="分类" name="cate"
                           rules={[{required: true, message: "请选择分类!"}]}>
                    <Select>
                        <Select.Option value="书籍">书籍</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="简介" name="describe"
                           rules={[{required: true, message: "请输入简介!"}]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="类别" name="sort"
                           rules={[{required: true, message: "请选择类别!"}]}>
                    <Select>
                        <Select.Option value="新品">新品</Select.Option>
                        <Select.Option value="经典">经典</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="价格" name="now_price"
                           rules={[{required: true, message: "请输入价格!"}]}>
                    <InputNumber/>
                </Form.Item>
                <Form.Item
                    name="cover"
                    label="上传封面"
                    rules={[
                        {
                            required: true,
                            message: '请上传封面!',
                        },
                    ]}
                    getValueFromEvent={normFile}
                    valuePropName="fileList">

                    <Upload
                        listType="picture-card"
                        showUploadList={false}
                        beforeUpload={beforeUpload}
                        maxCount={1}
                        onChange={uploadHandleChange}
                        customRequest={customRequest}
                    >
                        {imageUrl ? (
                            <img
                                src={imageUrl}
                                alt="avatar"
                                style={{width: '100%'}}
                            />
                        ) : (uploadButton)}
                    </Upload>
                </Form.Item>
                <Form.Item style={{paddingLeft: 250, marginTop: 50}}>
                    <Space>
                        <Button>重置</Button>
                        <Button type="primary"
                                onClick={() => confirmAdd()}>{editCourse ? '确认修改' : '确认添加'}</Button>
                    </Space>
                </Form.Item>
            </Form>
        },
        {
            key: 'video',
            label: editCourse ? '修改视频' : '添加视频',
            children: <Form
                form={form}
                style={{paddingTop: 30}}
                name="courseForm"
                labelCol={{span: 6}}
                wrapperCol={{span: 14}}
                layout="horizontal"
            >
                <Form.Item label="课程标题">
                    <Input/>
                </Form.Item>
                <Form.Item label="作者">
                    <Input/>
                </Form.Item>
                <Form.Item label="分类">
                    <Select>
                        <Select.Option value="书籍">书籍</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="简介">
                    <Input/>
                </Form.Item>
                <Form.Item label="价格">
                    <InputNumber/>
                </Form.Item>
                <Form.Item label="视频" valuePropName="fileList">
                    <Upload action="/upload.do" listType="picture-card">
                        <div>
                            <PlusOutlined/>
                        </div>
                    </Upload>
                </Form.Item>
                <Form.Item style={{paddingLeft: 250, marginTop: 50}}>
                    <Space>
                        <Button>重置</Button>
                        <Button type="primary">确认添加</Button>
                    </Space>
                </Form.Item>
            </Form>
        }
    ];

    const chooseFormRef = useRef()


    //删除操作成功
    const deleteCourseOk = async () => {
        try {
            setConfirmLoading(true);
            const result = await reqDeleteCourseById(courseId)
            if (result.status === 0) {
                setTimeout(async () => {
                    await getCourseListData()
                    setDeleteOpen(false);
                    setConfirmLoading(false);
                    message.success('删除课程成功!')
                }, 1000);
            }
        } catch (err) {
            message.error('删除课程失败！')
        }
    };
    const deleteCourseCancel = () => {
        setDeleteOpen(false);
    };

    return (
        <div>
            <Card>
                <div style={{display: 'flex', justifyContent: 'space-between'}}>
                    <Button type="primary" onClick={showDrawer}>新增</Button>
                    <Form ref={chooseFormRef} style={{display: 'flex'}} name="chooseForm">
                        <Space>
                            <Form.Item name="chooseSort">
                                <Select
                                    placeholder="在此筛选类别"
                                    style={{width: 150}}
                                    onChange={handleChange}
                                    options={[
                                        {
                                            value: '书籍',
                                            label: '书籍',
                                        },
                                        {
                                            value: '视频',
                                            label: '视频',
                                        },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item name="searchCourse">
                                <Input.Search onChange={searchCourse} placeholder="根据课程名称在此搜索"/>
                            </Form.Item>
                            <Form.Item>
                                <Button onClick={() => {
                                    getCourseListData()
                                    chooseFormRef.current.resetFields()
                                }}>重置</Button>
                            </Form.Item>
                        </Space>
                    </Form>
                </div>
                <Table
                    columns={columns}
                    dataSource={courseData}
                    pagination={{pageSize: 5}}
                    rowKey={record => record.id}
                />
            </Card>
            <Drawer
                title={editCourse ? '修改课程' : `新增课程`}
                placement="right"
                size="large"
                onClose={drawerClose}
                open={drawerOpen}
            >
                <Tabs
                    defaultActiveKey={tabKey}
                    items={tabItems}
                    onTabClick={handleTabClick}
                />
            </Drawer>
            <Modal
                centered
                title="确认删除所选项吗？"
                open={deleteOpen}
                onOk={deleteCourseOk}
                okText="确认删除"
                cancelText="取消"
                confirmLoading={confirmLoading}
                onCancel={deleteCourseCancel}
            >
                <p>删除之后不可恢复！</p>
            </Modal>
        </div>

    )
        ;
};

export default AdminCourse;